//
//  DKPhotoBrowserCell.m
//  xiaoquan
//
//  Created by 许建勇 on 15/8/31.
//  Copyright (c) 2015年 Alex. All rights reserved.
//

#import <MediaPlayer/MediaPlayer.h>
#import "DKPhotoBrowserCell.h"
#import "SDWaitingView.h"
#import "DKImageSqlite.h"


@interface DKPhotoBrowserCell()<DKPhotoModelDelegate,UIActionSheetDelegate,UIScrollViewDelegate>
/**
 *  滚动视图
 */
@property (nonatomic,strong) UIScrollView *contentView;


/**
 *  数据
 */
@property (nonatomic,strong) DKPhotoModel* model;

/**
 *  加载view
 */
@property (nonatomic,strong) SDWaitingView* loadingView;

/**
 *  长按的弹出按钮
 */
@property (nonatomic,strong) UIActionSheet *sheet;

/**
 *  视频的播放按钮
 */
@property (nonatomic,strong) UIImageView *videoSymbol;
@end

@implementation DKPhotoBrowserCell
#pragma mark - Init
- (void)initUI
{
    //滚动视图
    _contentView=[[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [_contentView setDelegate:self];
    [self addSubview:_contentView];
    //----------------------------------------------------------------------------------------
    //单击
    UITapGestureRecognizer* singleTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImage:)];
    singleTap.numberOfTapsRequired=1;
    [_contentView addGestureRecognizer:singleTap];
    
    //双击
    UITapGestureRecognizer* doubleTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImage:)];
    doubleTap.numberOfTapsRequired=2;
    [_contentView addGestureRecognizer:doubleTap];
    
    //双击失败后响应单击
    [singleTap requireGestureRecognizerToFail:doubleTap];
    
    //长按
    UILongPressGestureRecognizer *longTap=[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressImage:)];
    [_contentView addGestureRecognizer:longTap];
    
    
    //----------------------------------------------------------------------------------------
    //图片显示
    _imageView=[[UIImageView alloc] init];
    [_imageView setContentMode:UIViewContentModeScaleToFill];
    [_contentView addSubview:_imageView];
    
    //loading
    _loadingView=[[SDWaitingView alloc] init];
    [_loadingView setHidden:YES];
    [self addSubview:_loadingView];
    
    //视频播放按钮
    _videoSymbol=[[UIImageView alloc] init];
    [_videoSymbol setContentMode:UIViewContentModeScaleAspectFit];
    [_videoSymbol setHidden:YES];
    [_videoSymbol setImage:[UIImage imageNamed:@"videoSymbol"]];
    [_videoSymbol setUserInteractionEnabled:YES];
    [_videoSymbol addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMedia:)]];
    [self addSubview:_videoSymbol];
}

#pragma mark - Layout
- (void)refreshLayout:(CGRect)frame
{
    //滚动视图
    _contentView.frame=[UIScreen mainScreen].bounds;
    
    //loading
    _loadingView.frame=CGRectMake((_contentView.frame.size.width-kPhotoBrowserCellLoadingSize)/2,
                                  (_contentView.frame.size.height-kPhotoBrowserCellLoadingSize)/2,
                                  kPhotoBrowserCellLoadingSize,
                                  kPhotoBrowserCellLoadingSize);
    
    //视频播放按钮
    _videoSymbol.frame=_loadingView.frame;
}



#pragma mark - Setter
- (void)setPlaceHolderImage:(UIImage *)placeHolderImage
{
    _placeHolderImage=placeHolderImage;
    [_imageView setImage:_placeHolderImage];
    [self initToFitContent];
}




#pragma mark - Action
/**
 *  获取图片尺寸，若尺寸不够，则拉到全屏
 *
 *  @return 尺寸
 */
- (CGSize)convertImageSize
{
    CGSize size=_imageView.image.size;
    if(size.width==0 || size.height==0)
    {
        return CGSizeZero;
    }
    else
    {
        CGSize screenSize=[UIScreen mainScreen].bounds.size;
        if(size.width<screenSize.width && size.height<screenSize.height)
        {
            CGFloat widthKey=screenSize.width/size.width;
            CGFloat heightKey=screenSize.height/size.height;
            if(widthKey>heightKey)
            {//用高填充
                size.width*=heightKey;
                size.height*=heightKey;
            }
            else
            {//用宽填充
                size.width*=widthKey;
                size.height*=widthKey;
            }
            return size;
        }
        else
        {
            return size;
        }
    }
}


/**
 *  根据图片内容调整大小（初始化调整）
 */
- (void)initToFitContent
{
    //恢复缩放(非常重要)
    [_contentView setZoomScale:1];
    
    //屏幕尺寸
    CGSize screenSize=[UIScreen mainScreen].bounds.size;

    //图片尺寸
    CGSize imageSize=[self convertImageSize];
    
    if(CGSizeEqualToSize(imageSize, CGSizeZero))
    {
        return;
    }
    
    
    //调整图片显示
    _imageView.frame=CGRectMake(0,
                                0,
                                imageSize.width,
                                imageSize.height);
    
    //调整滑动范围
    _contentView.contentSize=CGSizeMake(imageSize.width,imageSize.height);
    
    //调整缩放
    if(self.model.type==DKPhotoObjectTypeMedia)
    {
        [_contentView setMaximumZoomScale:1.0];
        [_contentView setMinimumZoomScale:1.0];
        [self scrollViewDidZoom:_contentView];
    }
    else
    {
        [_contentView setMaximumZoomScale:MAX(1.0, MAX(screenSize.width/imageSize.width, screenSize.height/imageSize.height))];
        [_contentView setMinimumZoomScale:MIN(screenSize.width/imageSize.width, screenSize.height/imageSize.height)];
        [_contentView setZoomScale:_contentView.minimumZoomScale];
        [self scrollViewDidZoom:_contentView];
    }
}




/**
 *  单击或双击图片
 *
 *  @param recognizer 手势
 */
- (void)tapImage:(UITapGestureRecognizer *)recognizer
{
    if(recognizer.numberOfTapsRequired==1)
    {//退出浏览
        [[NSNotificationCenter defaultCenter] postNotificationName:kPhotoBrowserDismissNotificaiton object:nil];
    }
    else if(recognizer.numberOfTapsRequired==2)
    {//放大或缩小
        if(_contentView.zoomScale<(_contentView.maximumZoomScale+_contentView.minimumZoomScale)/2)
        {//放大
            CGPoint touchPoint=[recognizer locationInView:_imageView];
            [_contentView zoomToRect:CGRectMake(touchPoint.x,
                                                touchPoint.y,
                                                0,
                                                0)
                            animated:YES];
        }
        else
        {//缩小
            [_contentView setZoomScale:_contentView.minimumZoomScale animated:YES];
        }
    }
}

/**
 *  长按图片
 *
 *  @param recognizer 手势
 */
- (void)longPressImage:(UILongPressGestureRecognizer *)recognizer
{
    if(recognizer.state!=UIGestureRecognizerStateBegan)
    {
        return;
    }
    //文件大小
    NSString *sizeText=@"";
    long long videoSize=self.model.fileSize;
    if(videoSize>0)
    {
        if(videoSize<1024)
        {
            sizeText=[NSString stringWithFormat:@"(%lldK)",videoSize];
        }
        else
        {
            sizeText=[NSString stringWithFormat:@"(%.1fM)",videoSize*1.0/1024];
        }
    }
    
    
    if(self.model.type==DKPhotoObjectTypeMedia)
    {
        _sheet=[[UIActionSheet alloc] initWithTitle:nil
                                           delegate:self
                                  cancelButtonTitle:@"取消"
                             destructiveButtonTitle:nil
                                  otherButtonTitles:[NSString stringWithFormat:@"保存视频%@",sizeText],nil];
        _sheet.tag=1;
        [_sheet showInView:self];
    }
    else
    {
        if(self.model.isOrigin)
        {
            _sheet=[[UIActionSheet alloc] initWithTitle:nil
                                               delegate:self
                                      cancelButtonTitle:@"取消"
                                 destructiveButtonTitle:nil
                                      otherButtonTitles:[NSString stringWithFormat:@"保存图片%@",sizeText],nil];
            _sheet.tag=2;
            [_sheet showInView:self];
        }
    }
}

/**
 *  点击视频播放按钮
 *
 *  @param recognizer 手势
 */
- (void)tapMedia:(UITapGestureRecognizer *)recognizer
{
    if(self.model.type==DKPhotoObjectTypeMedia)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kPhotoBrowserDismissWithoutAnimationNotificaiton object:nil];
        MPMoviePlayerViewController* controller=[[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:self.model.url]];
        
        UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
        UIViewController *topVC = appRootVC;
        while (topVC.presentedViewController) {
            topVC = topVC.presentedViewController;
        }
        [topVC presentMoviePlayerViewControllerAnimated:controller];
    }
}





#pragma mark - UISrollViewDelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGFloat xcenter = scrollView.center.x , ycenter = scrollView.center.y;
    xcenter = scrollView.contentSize.width > scrollView.frame.size.width ? scrollView.contentSize.width/2 : xcenter;
    ycenter = scrollView.contentSize.height > scrollView.frame.size.height ? scrollView.contentSize.height/2 : ycenter;
    
    [_imageView setCenter:CGPointMake(xcenter, ycenter)];
}





#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(buttonIndex==0)
    {
        /*
        if(_sheet.tag==1)
        {//保存视频
            DKDownloadModel *model=[[DKDownloadHandler shareHandler] readyDownloadFile:self.model.url
                                                                              fileType:DKDownloadFileTypeVideo
                                                                              fileSize:self.model.fileSize];
            if(model.downloadState==DKDownloadFileStateDownloading)
            {
                [DKTopHUD pushContent:@"视频已在下载队列中"];
            }
            else
            {
                [DKTopHUD pushContent:@"开始下载"];
                [model startDownload];
            }
        }
        else if(_sheet.tag==2)
        {//保存图片
            UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }
         */
    }
}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    /*
    if(error==nil)
    {
        [DKTopHUD pushContent:@"图片保存成功"];
    }
    else
    {
        [DKTopHUD pushContent:@"图片保存失败"];
    }
     */
}




#pragma mark - DKPhotoModelDelegate
- (void)photoModel:(DKPhotoModel *)model didReceiveSize:(long long)receiveSize totalSize:(long long)totalSize image:(UIImage *)image isFinish:(BOOL)isFinish
{
    if(isFinish)
    {
        [self.loadingView setHidden:YES];
        if(self.model.isOrigin)
        {
            [self.imageView setImage:image];
        }
        else
        {//下载失败
            //[self.loadingView setMode:SDWaitingViewModeError];
            [self.imageView setImage:[UIImage imageNamed:@"默认展品图"]];
        }
        [self initToFitContent];
    }
    else
    {
        [self.loadingView setHidden:NO];
        if(totalSize==-1)
        {
            [self.loadingView setProgress:0.01];
        }
        else
        {
            [self.loadingView setProgress:receiveSize*1.0/totalSize];
        }
    }
}





#pragma mark - API
- (void)loadPhotoModel:(DKPhotoModel *)model
{
    //清除上一次的delegate
    if(self.model!=nil)
    {
        self.model.delegate=nil;
    }
    self.loadingView.hidden=YES;
    
    //设置本次的delegate
    self.model=model;
    self.model.delegate=self;
    if(self.model.isOrigin)
    {
        [[DKImageSqlite shareImageSqlite] loadImage:self.model.url
                                        placeHolder:nil
                                             target:nil
                                            process:nil
                                     enableDownload:NO
                                         completion:^(UIImage *imageData) {
                                             if(imageData!=nil)
                                             {
                                                 self.imageView.image=imageData;
                                                 [self initToFitContent];
                                             }
                                             else
                                             {
                                                 self.model.isOrigin=NO;
                                                 [self loadPhotoModel:self.model];
                                             }
                                         }];
    }
    else
    {
        self.loadingView.hidden=NO;
        self.loadingView.mode=SDWaitingViewModeLoopDiagram;
        [self.loadingView setProgress:self.model.process];
        if(!self.model.isDownload)
        {
            [self.model beginDownload];
        }
        
    }
    
    if(self.model.type==DKPhotoObjectTypeMedia)
    {
        self.videoSymbol.hidden=NO;
    }
    else
    {
        self.videoSymbol.hidden=YES;
    }
}


@end
